package com.small.nacos.naming.healthcheck;

import com.small.nacos.naming.misc.GlobalExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhoujin
 * @Date 2022/7/23 12:35
 */
public class HealthCheckReactor {

    private final static Logger LOGGER = LoggerFactory.getLogger(HealthCheckReactor.class);

    private static Map<String, ScheduledFuture> futureMap = new ConcurrentHashMap<>();

    public static void scheduleCheck(ClientBeatCheckTask task) {
        futureMap.computeIfAbsent(task.taskKey(),
                k -> GlobalExecutor.scheduleNamingHealth(task, 5000, 5000, TimeUnit.MILLISECONDS));
    }

    public static void cancelCheck(ClientBeatCheckTask task) {
        ScheduledFuture scheduledFuture = futureMap.get(task.taskKey());
        if (scheduledFuture == null) {
            return;
        }
        try {
            scheduledFuture.cancel(true);
            futureMap.remove(task.taskKey());
        } catch (Exception e) {
            LOGGER.error("[CANCEL-CHECK] cancel failed!", e);
        }
    }
}
